<template>
  <BasicDrawer @register="registerBaseDrawer" title="角色主体" width="750px" destroyOnClose>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" @click="handleCreate"> 新增用户</a-button>
        <a-button type="primary" @click="handleSelect"> 已有用户</a-button>

        <a-dropdown v-if="checkedKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="i-ant-design:down-outlined" />
          </a-button>
        </a-dropdown>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <UserDrawer @register="registerDrawer" @success="handleSuccess" />
    <UseSelectModal @register="registerModal" @select="selectOk" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, watch, unref } from "vue"
  import { BasicTable, useTable, TableAction } from "/@/components/Table"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import UserDrawer from "/@/views/system/user/UserForm.vue"
  import UseSelectModal from "./UseSelectModal.vue"
  import * as roleApi from "/@/api/iam/role"
  import { addUserRole } from "/@/api/sys/role"
  import { roleSubjectColumns, searchUserFormSchema } from "../role.data"
  import { getUserRoles } from "/@/views/system/tenantMember/user.api"
  import { Icon } from "/@/components/Icon"

  const emit = defineEmits(["register", "hideUserList"])
  const checkedKeys = ref<Array<string | number>>([])
  const roleId = ref("")
  const adminFlag = ref(false)
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerModal, { openModal }] = useModal()
  const [registerTable, { reload, updateTableDataRecord, setProps }] = useTable({
    title: "用户列表",
    columns: roleSubjectColumns,
    formConfig: {
      labelWidth: 75,
      schemas: searchUserFormSchema,
      showActionButtonGroup: false,
      autoSubmitOnEnter: true,
      // baseColProps: { lg: 12, md: 24 },
    },
    striped: true,
    useSearchForm: true,
    immediate: false,
    showTableSetting: true,
    clickToRowSelect: false,
    bordered: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    canResize: false,
    rowKey: "subjectId",
    actionColumn: {
      width: 50,
      title: "操作",
      dataIndex: "action",
      slots: { customRender: "action" },
      fixed: undefined,
    },
  })

  const rowSelection = {
    type: "checkbox",
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  }

  const [registerBaseDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    roleId.value = data.record.id
    adminFlag.value = data.adminFlag
    setProps({ 
      searchInfo: { roleId: roleId.value }, 
      api: adminFlag.value ? roleApi.pageAdminSubject : roleApi.pageSubject 
    })
    reload()
  })

  function onSelectChange(selectedRowKeys: (string | number)[], selectionRows) {
    checkedKeys.value = selectedRowKeys
  }

  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
      roleIds: [roleId.value],
      isRole: true,
    })
  }

  async function handleEdit(record: Recordable) {
    try {
      const userRoles = await getUserRoles({ userId: record.id })
      if (userRoles && userRoles.length > 0) {
        record.roleIds = userRoles
      }
    } catch (e) {
      console.log(e)
    }
    openDrawer(true, {
      record,
      isUpdate: true,
      isRole: true,
    })
  }

  async function handleDelete(record) {
    if (adminFlag.value) {
      await roleApi.deleteAdminRoleSubject({ subjectIds: [record.subjectId], roleId: roleId.value }, reload)
      return
    }
    await roleApi.deletebRoleSubject({ subjectIds: [ record.subjectId ], roleId: roleId.value }, reload)
  }

  async function batchHandleDelete() {
    if (adminFlag.value) { 
      await roleApi.batchDeleteAdminRoleSubject({ subjectIds: checkedKeys.value, roleId: roleId.value }, reload)
      return
    }
    await roleApi.batchDeleteRoleSubject({ subjectIds: checkedKeys.value, roleId: roleId.value }, reload)
  }

  function handleSuccess({ isUpdate, values }) {
    isUpdate ? updateTableDataRecord(values.id, values) : reload()
  }

  function handleSelect() {
    openModal(true)
  }

  async function selectOk(val) {
    await addUserRole({ roleId: roleId.value, userIdList: val }, reload)
  }

  function getTableAction(record) {
    return [
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
      },
      {
        label: "删除",
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
    ]
  }
</script>
